<?php

namespace App\Console\Commands\OpenShop;

use App\Models\OpenShop\Common\OpenShopProvinceTargetModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportProvinceTarget extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:import-province-target';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入省区年度目标';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址 : ');

        if (!$url) {
            $url = 'https://file.51kuafu.com/94/7b/d63258c289ea07eabaae4ffd6209d15a5098de6379b6764671d5d48f4b6c.xlsx';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new ProvinceTargetToCollection(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class ProvinceTargetToCollection implements ToCollection
{
    private string $errMsg = '';
    private int    $year   = 0;

    public function collection(Collection $collection)
    {
        // 校验列名
        $this->checkHeader($collection->first());
        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $provinceNames = $collection->pluck(0)->unique()->values();
        $provinces     = OpenShopOrganizationRegionMappingModel::query()->whereIn('provinceName', $provinceNames)->get()
                                                               ->keyBy('provinceName');

        $totalMonthNewNum = 0;
        $lastProvince     = 0;

        $collection = $collection->map(function ($item, $row) use ($provinces, &$totalMonthNewNum, &$lastProvince) {
            $row = $row + 1;

            if ($row == 1) {
                return null;
            }

            // 常规内容校验
            list($provinceName, $yearNewNum, $yearCloseNum, $yearStockNum, $date, $monthNewNum) = $item;
            $provinceCode = $provinces[$provinceName]['provinceCode'] ?? 0;
            if ($provinceCode != $lastProvince) {
                $totalMonthNewNum = 0;
                $lastProvince     = $provinceCode;
            }
            $totalMonthNewNum += $monthNewNum;

            $timestamp = $this->convertExcelDate($date);
            $yearMonth = date('Ym', $this->convertExcelDate($date));
            if (!$this->year) {
                $this->year = date('Y', $timestamp);
            }

            if (!$provinceCode) {
                $this->errMsg .= "第{$row}行，找不到的省份名称: {$provinceName}" . PHP_EOL;
            }

            if (!$yearMonth) {
                $this->errMsg .= "第{$row}行，月份错误: {$date}" . PHP_EOL;
            }

            return [
                'provinceCode' => $provinceCode,
                'yearMonth'    => $yearMonth,
                'timestamp'    => $timestamp,
                'openNum'      => $monthNewNum,
                'closeNum'     => 0,
                'stockNum'     => $totalMonthNewNum - $yearCloseNum,
                'yearNewNum'   => $yearNewNum,
                'yearCloseNum' => $yearCloseNum,
                'yearStockNum' => $yearStockNum,
            ];
        })->filter();

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        OpenShopProvinceTargetModel::query()->where('yearMonth', 'like', $this->year . '%')->delete();

        // 月份insert
        $monthData = $collection->map(function ($item) {
            $item              = (new OpenShopProvinceTargetModel)->fill($item)->toArray();
            $item['createdAt'] = time();
            $item['updatedAt'] = time();
            return $item;
        })->values()->toArray();

        OpenShopProvinceTargetModel::query()->insert($monthData);

        // 年份insert
        $yearData = $collection->keyBy('provinceCode')->map(function ($item) {
            $yearMonth = date('Y', $item['timestamp']);

            return [
                'provinceCode' => $item['provinceCode'],
                'yearMonth'    => $yearMonth,
                'openNum'      => $item['yearNewNum'],
                'closeNum'     => $item['yearCloseNum'],
                'stockNum'     => $item['yearStockNum'],
                'createdAt'    => time(),
                'updatedAt'    => time(),
            ];
        });

        OpenShopProvinceTargetModel::query()->insert($yearData->toArray());
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "省份",
            "全年新开目标合计",
            "全年闭店上限",
            "年底在营门店数合计",
            "月份",
            "本月新开目标",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

    private function convertExcelDate(?int $excelDate): int
    {
        $excelInitDate = 25569; // 1970的值

        if ($excelDate) {
            $excelTime = strtotime(date('Ymd', ($excelDate - $excelInitDate) * 86400 + 8 * 3600));
        } else {
            $excelTime = 0;
        }

        return (int)$excelTime;
    }
}
